package com.gzu.shop.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.gzu.shop.common.Result;
import com.gzu.shop.common.ResultStatus;
import com.gzu.shop.entity.Quest;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/ai")
public class AiController {

    public static GenerationParam createGenerationParam(List<Message> messages) {
        return GenerationParam.builder()
                .model("qwen-turbo")
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .build();
    }

    public static GenerationResult callGenerationWithMessages(GenerationParam param) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        return gen.call(param);
    }

    private static Message createMessage(Role role, String content) {
        return Message.builder().role(role.getValue()).content(content).build();
    }


    @SneakyThrows
    @PostMapping("/quest")
    public Result<String> addEntity(@RequestBody Quest quest) {
        System.out.println(quest.getQuest());
        List<Message> messages = new ArrayList<>();
        messages.add(createMessage(Role.SYSTEM, "You are a helpful assistant."));
        messages.add(createMessage(Role.USER, quest.getQuest()));
        GenerationParam param = createGenerationParam(messages);
        GenerationResult result = callGenerationWithMessages(param);
        System.out.println("模型输出：" + result.getOutput().getChoices().get(0).getMessage().getContent());
        messages.add(result.getOutput().getChoices().get(0).getMessage());
        String content = result.getOutput().getChoices().get(0).getMessage().getContent();
        return com.gzu.shop.common.Result.success(ResultStatus.SUCCESS, content);
    }
}
